import { extractTokenFromHeader, getUserFromToken } from '../utils/jwt';

export interface AuthenticatedEvent extends Event {
  context: {
    user: any;
  };
}

/**
 * 认证中间件
 * 解析JWT token并验证用户身份
 * 如果认证成功，将用户信息添加到event.context中
 * 只在API路径下生效，不影响前端页面访问
 */
export default defineEventHandler(async (event: AuthenticatedEvent) => {
  // 只对API路径应用认证中间件
  const url = getRequestURL(event);
  if (!url.pathname.startsWith('/api/')) {
    return;
  }

  // 获取Authorization请求头
  const authHeader = getHeader(event, 'authorization');
  
  // 提取token
  const token = extractTokenFromHeader(authHeader);
  
  // 白名单
  const whiteList = ['/api/user/login', '/api/user/register', '/api/user/send-code', '/api/user/verify-code','/api/user/user'];
  if (whiteList.includes(url.pathname)) {
    return;
  }
  
  if (!token) {
    throw createError({
      statusCode: 401,
      statusMessage: '未提供认证token'
    });
  }

  // 验证token并获取用户信息
  const user = await getUserFromToken(token);
  
  if (!user) {
    throw createError({
      statusCode: 401,
      statusMessage: '无效的token或用户不存在'
    });
  }

  // 将用户信息添加到event.context中，供后续API使用
  event.context.user = user;
});
